package com.caption.auth.secuity.sms;

import com.caption.auth.secuity.constant.SecurityConstant;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @description: 验证码登录过滤器
 * @author: 码农
 * @date: 2021-12-31 20:26:11
 */
public class SmsCodeAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    /**
     * 是否只支持post请求
     */
    private boolean postOnly = true;

    /**
     * 设置验证码登录地址
     */
    public SmsCodeAuthenticationFilter() {
        super(new AntPathRequestMatcher(SecurityConstant.SMS_LOGIN_URL, SecurityConstant.SMS_LOGIN_METHOD));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        if (postOnly && !"POST".equals(request.getMethod())) {
            throw new AuthenticationServiceException("authentication method not supported:" + request.getMethod());
        }
        String mobile = obtainMobile(request);
        if (mobile == null) {
            mobile = "";
        }
        mobile = mobile.trim();
        //构建SmsCodeAuthenticationToken 返回
        SmsCodeAuthenticationToken smsCodeAuthenticationToken = new SmsCodeAuthenticationToken(mobile);
        setDetails(request, smsCodeAuthenticationToken);
        return this.getAuthenticationManager().authenticate(smsCodeAuthenticationToken);
    }

    protected void setDetails(HttpServletRequest request, SmsCodeAuthenticationToken smsCodeAuthenticationToken) {
        smsCodeAuthenticationToken.setDetails(authenticationDetailsSource.buildDetails(request));
    }

    protected String obtainMobile(HttpServletRequest request) {
        return request.getParameter(SecurityConstant.MOBILE_KEY);
    }

}
